package com.laxcen.basiclib.core.location;

import android.content.Context;

import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeAddress;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.laxcen.basiclib.BaseApp;
import com.laxcen.basiclib.utils.DateUtil;
import com.laxcen.basiclib.utils.LogUtil;
import com.laxcen.basiclib.utils.StringUtil;

import java.util.Date;

/**
 *  定位
 */
public class LocationHelper {
    private static GeocodeSearch geocoderSearch;
    private static AMapLocationClient locationClient;

    public static LocationInfo locationInfo;

    //销毁定位器
    public static void destroyLocation(){
        if(locationClient!=null){
            LogUtil.e("location","destroyLocation");
            locationClient.onDestroy();
            locationClient = null;
        }
    }
    private static Date lastDate;

    /**
     * 获取定位信息
     * @param useHistory
     * @param onResult
     */
    public static void getLocation(boolean useHistory, OnResult onResult){
        if(locationInfo==null){
            locationInfo= new LocationInfo();
        }
        if(useHistory&&!StringUtil.isEmpty(locationInfo.getAddress())){
            if(lastDate==null){
                long t = new Date().getTime()+1*15*1000;//15秒后
                lastDate = new Date(t);
            }
            LogUtil.e(" onLocationChanged","lastDate", DateUtil.format(lastDate,null));
            if((locationInfo.getLatitude()>0&&locationInfo.getLongitude()>0)
                    &&new Date().before(lastDate)){
                //两分钟前 使用已有的地址
                if(onResult!=null){
                    LogUtil.e("onLocationChanged","使用了历史地址",locationInfo.getLatitude() ,locationInfo.getLongitude(),locationInfo.getAddress());
                    onResult.onSuccess(locationInfo);
                }
                return;
            }else{
                //两分钟后获取地址 再推迟两分钟
                long t = new Date().getTime()+2*60*1000;
                lastDate = new Date(t);
                locationInfo = null;
            }
        }
        if(locationClient==null) {
            locationClient = new AMapLocationClient(BaseApp.getApp());
            AMapLocationClientOption option = new AMapLocationClientOption();
            //设置高精度定位
            option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            option.setGpsFirst(true);
            //获取3秒内精度最高的结果
            option.setOnceLocationLatest(true);
            //不允许模拟定位
            option.setMockEnable(false);
            option.setInterval(1000 * 10);
            option.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn);
            locationClient.setLocationOption(option);
        }
        toStartLocation(onResult);
    }
    private static  void toStartLocation(OnResult onResult){
        locationClient.setLocationListener(aMapLocation -> {
            if (aMapLocation.getErrorCode() == 0) {
                locationInfo = new LocationInfo();
                if (!StringUtil.isEmpty(aMapLocation.getAddress())) {
                    locationInfo.setAddress(aMapLocation.getAddress());
                }
                if (!StringUtil.isEmpty(aMapLocation.getPoiName())) {
                    locationInfo.setAddressName(aMapLocation.getPoiName());
                }
                if (!StringUtil.isEmpty(aMapLocation.getCity())) {
                    locationInfo.setCity(aMapLocation.getCity());
                }
                if (!StringUtil.isEmpty(aMapLocation.getCountry())) {
                    locationInfo.setCountry(aMapLocation.getCountry());
                }
                if (!StringUtil.isEmpty(aMapLocation.getDistrict())) {
                    locationInfo.setDistrict(aMapLocation.getDistrict());
                }
                if (!StringUtil.isEmpty(aMapLocation.getFloor())) {
                    locationInfo.setFloor(aMapLocation.getFloor());
                }
                if (!StringUtil.isEmpty(aMapLocation.getProvince())) {
                    locationInfo.setProvince(aMapLocation.getProvince());
                }
                if (!StringUtil.isEmpty(aMapLocation.getRoad())) {
                    locationInfo.setRoad(aMapLocation.getRoad());
                }
                if (!StringUtil.isEmpty(aMapLocation.getStreet())) {
                    locationInfo.setStreet(aMapLocation.getStreet());
                }
                if (aMapLocation.getLatitude() > 0) {
                    locationInfo.setLatitude(aMapLocation.getLatitude());
                }
                if (aMapLocation.getLongitude() > 0) {
                    locationInfo.setLongitude(aMapLocation.getLongitude());
                }
                if (onResult != null) {
                    onResult.onSuccess(locationInfo);
                }
                destroyLocation();
            } else {
                if (onResult != null) {
                    onResult.onError();
                }
            }
        });
        if(null != locationClient){
            locationClient.stopLocation();
            locationClient.startLocation();
        }
    }

    /**
     * 根据地址获取位置
     * @param context
     * @param city
     * @param address
     * @param onResult
     */
    public static void getLocationByAddress(Context context,String city, String address, final OnResult onResult){
        if(geocoderSearch==null){
            geocoderSearch = new GeocodeSearch(context);
            geocoderSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
                @Override
                public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {}

                @Override
                public void onGeocodeSearched(GeocodeResult geocodeResult, int rCode) {
                    if(rCode==1000){
                        if(geocodeResult.getGeocodeAddressList()!=null&&geocodeResult.getGeocodeAddressList().size()>0){
                            GeocodeAddress geocodeAddress = geocodeResult.getGeocodeAddressList().get(0);
                            LatLonPoint latLonPoint = geocodeAddress.getLatLonPoint();
                            LocationInfo locationInfo = new LocationInfo();
                            locationInfo.setLongitude(latLonPoint.getLongitude());
                            locationInfo.setLatitude(latLonPoint.getLatitude());
                            locationInfo.setAddress(geocodeAddress.getFormatAddress());
                            onResult.onSuccess(locationInfo);
                        }else{
                            onResult.onError();
                        }
                    }else{
                        onResult.onError();
                        //   LogUtil.e("onGeocodeSearched","失败"+rCode);
                    }
                }
            });
        }
        GeocodeQuery query = new GeocodeQuery(address, city);
        geocoderSearch.getFromLocationNameAsyn(query);
    }
    public interface OnResult{
        void onSuccess(LocationInfo locationInfo);
        void onError();
    }

}
